# -*- coding: utf-8 -*-
from flask import Blueprint, request, jsonify, url_for
import http.client
import urllib
import json
import base64
from app.utils.file_utils import save_image_file
from app.models import User, ImageRecord
from app.extensions import db
from app.utils.jwt_token import jwt_tools

image_bp = Blueprint('image_bp', __name__)

TIAN_API_KEY = 'cfe6e6a802f6bb5f40b0b4bb2767a0c1'  # 替换为真实api


@image_bp.route('/api/classify-image', methods=['POST'])
def classify_image():
    try:
        # 获取上传文件
        file = request.files.get('file')
        token = request.headers.get('Authorization').split()[1]
        openid = jwt_tools.parse_token(token)[0]['openid']
        # openid = request.form.get('openid')

        if not file or not openid:
            return jsonify({'code': 400, 'msg': 'Missing file or openid'}), 400

        # 查找用户 ID（你需要实现 get_user_by_openid）
        user = User.get_user_by_openid(openid)
        if not user:
            return jsonify({'code': 404, 'msg': 'User not found'}), 404
        # 保存图片到服务器，返回路径
        rel_path, abs_path = save_image_file(file, user.id)

        # 重新读取保存后的图片文件并转为 base64（防止 file.read() 已被消费）
        with open(abs_path, 'rb') as f:
            img_bytes = f.read()
        img_base64 = base64.b64encode(img_bytes).decode('utf-8')

        # 调用天行图像识别 API
        conn = http.client.HTTPSConnection('apis.tianapi.com')
        params = urllib.parse.urlencode({
            'key': TIAN_API_KEY,
            'img': img_base64
        })
        headers = {'Content-type': 'application/x-www-form-urlencoded'}
        conn.request('POST', '/imglajifenlei/index', params, headers)
        tianapi = conn.getresponse()
        result = tianapi.read()
        data = json.loads(result.decode('utf-8'))

        # 存数据库用相对路径
        record = ImageRecord(user_id=user.id, image_url=url_for('static', filename=rel_path, _external=True), predicted_class=data.get('result', {}))
        db.session.add(record)
        db.session.commit()

        # 返回识别结果
        return jsonify({
            'code': 200,
            'msg': 'success',
            'result': data.get('result', {}),
        })

    except Exception as e:
        return jsonify({'code': 500, 'msg': str(e)}), 500
